<?php
namespace app\index\controller;

use app\index\validate\LoginValidate;
use app\index\validate\RegisterValidate;
use think\Controller;
use think\Request;
use think\Session;
use think\Validate;

class Index extends Controller
{
    public function index()
    {
        return view();
    }

    /**
     * 登录
     */
    public function login(){
        $data['name'] = input("post.username");
        $data['password'] = input("post.password");
        $result =  $this->validate($data,LoginValidate::class);
        if(true !== $result) {
            $this->error($result);
        }
        $result =    model('user')->where($data)->find();
        session('name',$data['name']);
        session('id',$result['id']);
        if($result){
            $this->success("登陆成功",$_SERVER['HTTP_REFERER']);
        }else{
            $this->error("账号密码输入有误");
        }
        return view();
    }

    /**
     * 注册
     */
    public function register()
    {
        # code...
        $data = input("post.");
        $result =  $this->validate($data,RegisterValidate::class);
        if(true !== $result){
            $this->error($result);
        }
        $result =    model('user')->save($data);
        if($result){
            $this->success("注册成功",$_SERVER['HTTP_REFERER']);
        }else{
            $this->error("注册失败");
        }
        return view();
    }
    
    public function loginOut(){
        session(null);
        if (session('?admin.id')) {
            $this->error('退出失败！');
        } else {
            $this->success('退出成功', 'index/index/index');
        }
    }
}
